package com.shaoshaohuo.app.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.NewCarFragmentAdapter;
import com.shaoshaohuo.app.entity.FragmentNewCarEntity;
import com.shaoshaohuo.app.entity.NewCarlistEntity;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpConfig;
import com.shaoshaohuo.app.net.NewHttpCofig;
import com.shaoshaohuo.app.net.RequestParam;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.ui.MainTabActivity;
import com.shaoshaohuo.app.ui.SureOrderPayInformation;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.utils.ToastUtil;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 购物车
 * Created by Administrator on 2017/6/6.
 */

public class NewCartFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, NewCarFragmentAdapter.AdaterListener, View.OnClickListener {
    private View carshop_emptyview;
    private SwipeRefreshLayout carshop_swp;
    private ListView loadlistview;
    private Button button;
    private TextView carshop_money;
    private CheckBox carshop_allseleter;
    private Button carshop_settlement;
    private NewCarFragmentAdapter newCarFragmentAdapter;
    private ArrayList<NewCarlistEntity> strings;
    private Handler handler = new Handler();
    private TextView textview_message;
    private View clickbar;

    private String type;//1是从普通水果过来2是采摘

    public static NewCartFragment newInstance(String type) {
        Bundle args = new Bundle();
        args.putString("type", type);
        NewCartFragment fragment = new NewCartFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_newcarlayout, null);
        Bundle arguments = getArguments();
        this.type = arguments.getString("type");
        return inflate;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        viewlistener();
        initdate();

    }


    @Override
    public void onResume() {
        super.onResume();
        Log.e("TAG", "onResume: ");
        //在这里刷新
        carshop_swp.post(new Runnable() {
            @Override
            public void run() {
                carshop_swp.setRefreshing(true);
                onRefresh();
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.e("TAG", "onHiddenChanged: " + hidden);
        if (!hidden) {
            //刷新
            carshop_swp.post(new Runnable() {
                @Override
                public void run() {
                    carshop_swp.setRefreshing(true);
                    onRefresh();
                }
            });
        } else {
            carshop_swp.setRefreshing(false);
        }
    }


    /**
     * 网络请求的方法
     */
    private void netdate() {
        Map<String, String> headerParams = RequestParam.getHeaderParams();
//        headerParams.put("userid", "32237");
//        headerParams.put("usertoken", "d99duJgC6uyZsqvLK4abD3H%2BKqHIcni%2FylO9Hn5kBE7AhJ2goQg6a4aRpm%2BNCWwgie3rmalwygxPpxacX3BL88VD0DADuC2IXJLGPkQ7vIy%2BVRkaglXmMf6CLZ2JXfYuSPc2AEDnuNPF0BVanvbMb8kLKX4yBQT%2Fh6ZtF4ocqEhbdCEDnBoHp3HvyTNomYPurxT8ccs6T2aZZe84wshnkcFTw6hCfR%2BUzE0xMHMd7uggt7XB%2FUuezUYW7f1ETD6K4aDjqvBCMgDzW53X%2BMIw3xbEXvfEc%2FwWe54EowS2PmkKXtvVEWxvkvrboBSf5Q%2F8y2AQFeSbmrkzcYKtdwiqy4CucpTh%2F5D2PehpyMssJVq5JPQzU4MrWxsSf0%2B%2FkGcT3J4atV2bkpFrAq1%2B");
        Okhttputils.Instanse(getContext()).getnet(headerParams, getContext(), HttpConfig.BASE_HOST_URL + NewHttpCofig.App_CarGET, new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {

            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                FragmentNewCarEntity o1 = (FragmentNewCarEntity) o;
                List<FragmentNewCarEntity.DataBean> data = o1.getData();

                //NewCarlistEntity
                final ArrayList<NewCarlistEntity> newCarlistEntities = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    NewCarlistEntity newCarlistEntity = new NewCarlistEntity();
                    newCarlistEntity.setDataBean(data.get(i));
                    List<NewCarlistEntity> getdata = newCarFragmentAdapter.getdata();
                    if (getdata.size() > i) {
                        boolean ischecked = getdata.get(i).ischecked();
                        int postion = getdata.get(i).getPostion();
                        newCarlistEntity.setIschecked(ischecked);
                        newCarlistEntity.setPostion(postion);
                    } else {
                        newCarlistEntity.setIschecked(false);
                    }

                    newCarlistEntities.add(newCarlistEntity);
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (newCarlistEntities.size() > 0) {
                            clickbar.setClickable(false);
                        } else {
                            clickbar.setClickable(true);
                        }

                        newCarFragmentAdapter.setData(newCarlistEntities);
                        carshop_swp.setRefreshing(false);
                        //结算处理
                        Overmoney(newCarlistEntities);
                    }
                });
            }
        }, FragmentNewCarEntity.class);

    }

    /*
    結算處理
     */
    private void Overmoney(List<NewCarlistEntity> newCarlistEntities) {
        int allnum = 0;
        float allmoney = 0;
        for (int i = 0; i < newCarlistEntities.size(); i++) {
            if (newCarlistEntities.get(i).ischecked()) {
                String num = newCarlistEntities.get(i).getDataBean().getNum();
                Integer integer = Integer.valueOf(num);
                String price = newCarlistEntities.get(i).getDataBean().getPrice();
                float aFloat = Float.valueOf(price);
                int mbn_details = newCarlistEntities.get(i).getDataBean().getMbn_details();
                float v = aFloat * integer * mbn_details;
                allmoney += v;
                allnum += integer;
            }
        }
        //赋值
//        allmoney = Float.valueOf(StringUtil.zeor(allmoney + ""));
        Log.e("allmoney", allmoney + "");
        BigDecimal b = new BigDecimal(allmoney);
        float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        carshop_settlement.setText("结算" + allnum);
        carshop_money.setText("¥" + f1);

    }

    private void initdate() {
        strings = new ArrayList<>();
        newCarFragmentAdapter = new NewCarFragmentAdapter(getContext(), strings, true, "1");
        loadlistview.setAdapter(newCarFragmentAdapter);
        newCarFragmentAdapter.setAdapterListener(this);

    }

    private void viewlistener() {
        carshop_allseleter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //全选按钮
                List<NewCarlistEntity> getdata = newCarFragmentAdapter.getdata();
                for (int i = 0; i < getdata.size(); i++) {
                    getdata.get(i).setIschecked(isChecked);
                }
                newCarFragmentAdapter.notifyDataSetChanged();

            }
        });
        carshop_swp.setOnRefreshListener(this);
        textview_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String catids = "";
                final List<NewCarlistEntity> getdata = newCarFragmentAdapter.getdata();
                for (int i = 0; i < getdata.size(); i++) {
                    NewCarlistEntity newCarlistEntity = getdata.get(i);
                    boolean ischecked = newCarlistEntity.ischecked();
                    if (ischecked && catids.length() > 0) {
                        catids += "_" + newCarlistEntity.getDataBean().getOrderid();

                    } else if (ischecked && catids.length() == 0) {
                        catids += newCarlistEntity.getDataBean().getOrderid();
                    }
                }
                Log.e("TAG", "onClick: " + catids);
                ShopHttpConfig.deletshop(getContext(), catids, new Okhttputils.OkutListener() {
                    @Override
                    public void error(Call call, IOException e) {

                    }

                    @Override
                    public void error(Call call, int code) {

                    }

                    @Override
                    public void suseff(Call call, Response response, Object o) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                List<NewCarlistEntity> getdata1 = newCarFragmentAdapter.getdata();
                                for (int i = 0; i < getdata1.size(); i++) {
                                    getdata1.get(i).setIschecked(false);
                                }
                                if (!type.equals("1")) {
                                    MainTabActivity activity = (MainTabActivity) getActivity();
                                    activity.setnum();
                                }

                                if (carshop_allseleter.isChecked()) {
                                    carshop_allseleter.setChecked(false);
                                }
                                carshop_swp.setRefreshing(true);
                                onRefresh();

                            }
                        });
                    }
                });
            }
        });

    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void init(View view) {
        carshop_emptyview = view.findViewById(R.id.carshop_emptyview);
        carshop_swp = (SwipeRefreshLayout) view.findViewById(R.id.carshop_swp);
        loadlistview = (ListView) view.findViewById(R.id.carshop_load);
        clickbar = view.findViewById(R.id.clickbar);
        loadlistview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem == 0) {
                    view.getParent().getParent().requestDisallowInterceptTouchEvent(false);
                } else {
                    carshop_swp.setRefreshing(false);
                    view.getParent().getParent().requestDisallowInterceptTouchEvent(true);
                }
            }
        });
        loadlistview.setEmptyView(carshop_emptyview);
        //去逛逛按钮
        button = (Button) view.findViewById(R.id.carshop_Go);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type.equals("1")) {
                    //详情页
                    SharedPreferencesHelper.setBoolean(v.getContext(), SharedPreferencesHelper.Field.HOME, true);
                    getActivity().finish();
                } else {
                    MainTabActivity activity = (MainTabActivity) getActivity();
                    activity.setcur(0);
                }

            }
        });
        carshop_money = (TextView) view.findViewById(R.id.carshop_money);
        carshop_allseleter = (CheckBox) view.findViewById(R.id.carshop_allseleter);
        //结算
        carshop_settlement = (Button) view.findViewById(R.id.carshop_settlement);
        carshop_settlement.setOnClickListener(this);
        //topbarview的赋值及监听
        textview_message = (TextView) view.findViewById(R.id.textview_message);
        textview_message.setVisibility(View.VISIBLE);
        textview_message.setText("删除");
        textview_message.setTextColor(Color.WHITE);
        ImageView imageview_message = (ImageView) view.findViewById(R.id.imageview_message);
        imageview_message.setVisibility(View.GONE);
        //toolbar_topname
        TextView toolbar_topname = (TextView) view.findViewById(R.id.toolbar_topname);
        toolbar_topname.setVisibility(View.VISIBLE);
        toolbar_topname.setText("购物车");
    }

    @Override
    public void onRefresh() {
//        ToastUtil.toast("刷新");
        netdate();
    }

    @Override
    public void whlistener() {
        if (!type.equals("1")) {
            MainTabActivity mainTabActivity = (MainTabActivity) getActivity();
            mainTabActivity.setnum();
        }

        Overmoney(newCarFragmentAdapter.getdata());
    }

    @Override
    public void chekedelistener(boolean ischecked) {
        Overmoney(newCarFragmentAdapter.getdata());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.carshop_settlement:
                FragmentNewCarEntity fragmentNewCarEntity = new FragmentNewCarEntity();
                List<NewCarlistEntity> getdata = newCarFragmentAdapter.getdata();
                List<FragmentNewCarEntity.DataBean> dataBeen = new ArrayList<>();
                fragmentNewCarEntity.setData(dataBeen);
                Intent intent = new Intent();
                for (NewCarlistEntity d : getdata) {
                    String goodStatus = d.getDataBean().getGoodStatus();
                    boolean ischecked = d.ischecked();
                    if (ischecked) {
                        FragmentNewCarEntity.DataBean dataBean = d.getDataBean();
                        dataBeen.add(dataBean);
                    }

                }
                if (dataBeen.size() > 0) {
                    for (int i = 0; i < dataBeen.size(); i++) {
                        if (dataBeen.get(i).getGoodStatus().equals("2")) {
                            ToastUtil.toast("商品已过期");
                            return;
                        }
                    }
                    intent.putExtra("fragmentNewCarEntity", fragmentNewCarEntity);
                    intent.setClass(getContext(), SureOrderPayInformation.class);
                    intent.putExtra("gotype", "1");//购物车到订单
                    intent.putExtra("sorttype", "1");//普通商品
                    startActivity(intent);
                } else {
                    ToastUtil.toast("请选择商品");
                }
                break;
        }
    }
}
